import { _decorator, Component, director, EventTouch, Node, Sprite, SpriteFrame, v2, v3, Vec2 } from 'cc';
import { AnimalType, CustomEventType } from './GlobalEnum';
const { ccclass, property } = _decorator;
const tmpV2_0 = v2();
const tmpV2_1 = v2();
@ccclass('CldObj')
export class CldObj extends Component {
    curType: AnimalType;
    sf: SpriteFrame;

    curWpos = v3();
    tarWpos = v3();

    angle = 0;

    protected onLoad(): void {
        this.initTouch();
    }

    init(name: AnimalType, sf: SpriteFrame) {
        this.curType = name;
        this.sf = sf;
        this.node.getChildByName('icon').getComponent(Sprite).spriteFrame = this.sf;

        this.curWpos.set(this.node.worldPosition);
        this.tarWpos.set(this.node.worldPosition);
    }

    protected update(dt: number): void {
        this.curWpos.lerp(this.tarWpos, 0.3);
        this.node.setWorldPosition(this.curWpos);
    }

    //#region --
    onClose() {
        setTimeout(() => {
            this.node.removeFromParent();
            this.node.destroy();
        }, 0);
    }

    //#endregion


    //#region ----触摸事件---

    onTouchEvents() {
        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }
    initTouch() {
        //
        this.onTouchEvents();
    }
    enableTouch() {

    }
    disableTouch() {

    }
    updateTouch(dt) {

    }

    onTouchStart(event) {
        event.getUILocation(tmpV2_0);

    }

    onTouchMove(event: EventTouch) {
        event.getUILocation(tmpV2_0);
        director.emit(CustomEventType.FormatWpos, tmpV2_0);
        this.tarWpos.set(tmpV2_0.x, tmpV2_0.y, 0);
    }

    onTouchEnd(event: EventTouch) {
        event.getUIStartLocation(tmpV2_0);
        event.getUILocation(tmpV2_1);

        if (tmpV2_1.subtract(tmpV2_0).length() < 5) {
            // 视为点击            
            this.angle = (this.angle + 90) % 360;
            this.node.angle = this.angle;
        }

    }

    //#endregion



}


